package com.yyxxlu.aimodel.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.yyxxlu.aimodel.service.DashscopeSrevice;
import io.reactivex.Flowable;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class DashscopeSreviceImpl implements DashscopeSrevice {
    private static StringBuilder fullContent = new StringBuilder();
    private static GenerationParam buildGenerationParam(Message userMsg) {

        return GenerationParam.builder()
                .apiKey("sk-90e295249b264fbe9e2dfe9d84dc06dd")
                .model("qwen-plus")
                .messages(Arrays.asList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)
                .build();
    }
    private static StringBuilder handleGenerationResult(GenerationResult message) {
        String content = message.getOutput().getChoices().get(0).getMessage().getContent();
        fullContent.append(content);
        System.out.println(content);
        return fullContent.append(content);
    }
    public static Flowable<GenerationResult> streamCallWithMessage(Generation gen, Message userMsg)
            throws NoApiKeyException, ApiException, InputRequiredException {
        GenerationParam param = buildGenerationParam(userMsg);
        System.out.println("流式输出内容为：");
        Flowable<GenerationResult> result = gen.streamCall(param);
        result.blockingForEach(DashscopeSreviceImpl::handleGenerationResult);
        return result;
        // result.blockingForEach(DashscopeSreviceImpl::handleGenerationResult);
        // System.out.println("完整内容为: " + fullContent.toString());
    }
    @Override
    public Flowable<GenerationResult> chat(String question) {
        try{
            Generation gen = new Generation();
            Message userMsg = Message.builder().role(Role.USER.getValue()).content(question).build();
            Flowable<GenerationResult> result =streamCallWithMessage(gen, userMsg);
            return result;
        }catch (Exception e){

        }
        return null;
    }
}
